﻿using System;
using System.Collections.Generic;
using System.IO;

namespace SmartMotion.Core
{
    public class IOMgr
    {
        #region 常用功能

        //AddIO
        //DeleIO
        //ModifyIO
        //getIOInfo
        //GetAllIOName
        //GetIONameByCard
        //DeleteIOLists
        //AddIOLists
        //GetAllIO

        #endregion 常用功能

        #region 单例

        private static readonly Lazy<IOMgr> Instance = new Lazy<IOMgr>(() => new IOMgr());

        private IOMgr()
        {
            _cards = new List<IIOCtrl>();
            IOConfigPath = Environment.CurrentDirectory + "\\Config\\";
            if (!Directory.Exists(IOConfigPath))
            {
                Directory.CreateDirectory(IOConfigPath);
            }
        }

        public static IOMgr Ins { get; } = Instance.Value;

        #endregion 单例

        private readonly List<IIOCtrl> _cards;
        public  readonly string IOCtrl = "IOCtrl";
        public string IOConfigPath { get; set; }

        public string IOConfigFileName
        {
            get
            {
                return IOConfigPath + "IOConfig.cfg";
            }
        }


        public string CardFilePath { get; set; }    

        public List<IIOCtrl> Cards
        {
            get
            {
                foreach (var varInfo in GlobalVars.Ins.Vars[GlobalVars.IOMgr].Values)
                {
                    if (varInfo.Group != IOCtrl) continue;
                    if (!_cards.Contains(varInfo.Value))
                    {
                        _cards.Add(varInfo.Value);
                    }
                }
                    
                return _cards;
            }
        }

        public void Load()
        {
            GlobalVars.Ins.LoadDic(GlobalVars.IOMgr, IOConfigFileName,false);

            foreach (var iOCardInterface in Cards)
            {
                for (int j = 0; j < iOCardInterface.DIID.Count; j++)
                {
                    iOCardInterface.DI.Add(GlobalVars.Ins.GetVar(iOCardInterface.DIID[j]).Value);
                }

                for (int j = 0; j < iOCardInterface.DOID.Count; j++)
                {
                    iOCardInterface.DO.Add(GlobalVars.Ins.GetVar(iOCardInterface.DOID[j]).Value);
                }

            }

        }

        public void Save()
        {
            GlobalVars.Ins.SaveDic(GlobalVars.IOMgr, IOConfigFileName);
        }
    }
}